<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\Address;
use App\Models\Category;
use App\Models\OrderProduct;
use App\Models\Product;
use App\Models\ProductImage;
use App\Rules\NumericRule;
use App\Rules\StatusRule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ProductController extends Controller
{


    /**
     * 所有商品分类
     * @return array
     */
    public function getCategories(Request $request){
        $type = $request->get('type', 'all');
        $query = Category::where('status',1);
        switch ($type) {
            case 'all': {
                break;
            }
            case 'nav': {
                $query = $query->where('show_in_nav', 1);
            }
            default: break;
        }
        $cate = $query->orderBy('sort_order')->get();
        return[
            "result" => 'success',
            "data" => $cate
        ];

    }

    /**
     * 获取商品列表
     * @param Request $request
     * @return array
     */
    public function productList(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => "required"
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        $inProducts = getAddressProducts($user->id,null,null,null);

        $products = Product::where('domestic',0)
            ->where('verify',1)
            ->where('shelves',1)
            ->union($inProducts)
            ->orderBy('created_at')
            ->paginate(10);
        return [
            "result" => "success",
            "data" => $products
        ];
    }

    /**
     * 根据分类ID获取商品列表
     * @param Request $request
     * @return array
     */
    public function getCategoryProducts(Request $request,$id){
        $validator = Validator::make($request->all(), [
            'openid' => "required"
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        $inProducts = getAddressProducts($user->id,null,$id,null);
        $products = Product::where('domestic',0)
            ->union($inProducts)
            ->where('verify',1)
            ->where('shelves',1)
            ->where('cate_id',$id)
            ->paginate(10);
        return [
            "result" => "success",
            "data" => $products
        ];
    }

    /**
     * 获取精选商品列表
     */
    public function getFeatureProducts(Request $request)
    {
        $user = getUser($request);
        $inProducts = getAddressProducts($user->id,null,null,null);
        $products = Product::where('verify',1)
            ->where('shelves',1)
            ->where('domestic',0)
            ->union($inProducts)
            ->orderBy('updated_at')
            ->orderBy('stock')
            ->orderBy('price')
            ->paginate(10);
        return [
            "result" => "success",
            "data" => $products
        ];
    }


    /**
     * 商品搜索
     * @param Request $request
     * @return array
     */
    public function searchProducts(Request $request){
        $validator = Validator::make($request->all(), [
            'name' => "required",
            'openid' => "required",
            'type' => ['nullable',new NumericRule],
            'order_type' => ['nullable',new StatusRule],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }

        $user = getUser($request);
        $inProducts = getAddressProducts($user->id,$request->get('name'),null,$request->get('type'));
        $sort = $request->get('order_type');
        $list = Product::where('name','like','%'.$request->get('name').'%')
            ->when($request->get('type'),function ($query)use($request){
                return $query->where('activity_type',$request->get('type'));
            })
            ->where('domestic',0)
            ->where('verify',1)
            ->where('shelves',1)
            ->union($inProducts)
            ->when($request->get('order_type'),function ($query)use($sort){
                switch ($sort){
                    case "price_up":{
                        return $query->orderBy("price");
                    }break;
                    case "price_down":{
                        return $query->orderBy('price','desc');
                    }break;
                    case "sales_volume":{
                        return $query->orderBy('volume','desc');
                    }break;
                    case "newest_shelves":{
                        return $query->orderBy('created_at','desc');
                    }break;
                }
            })
            ->paginate(10);

        return [
            'result'=>'success',
            'data'=>$list
        ];
    }

    /**
     * 商品详情
     * @param $id
     * @return array
     */
    public function productDetail(Request $request,$id){
        $validator = Validator::make($request->all(), [
            'openid' => "required",
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $product = Product::findOrFail($id);
        $main_img = ProductImage::where('product_id',$id)->where('type',1)->get();
        $detail_img = ProductImage::where('product_id',$id)->where('type',2)->get();
        $activity_img = ProductImage::where('product_id',$id)->where('type',3)->get();

        //判断当前商品能不能被分享：1，用户被允许可以分享 2，商品是外销产品
        $user = getUser($request);
        $share = 0;
        if ($user['has_share'] && $product['domestic'] == 0){
            $share = 1;
        }
        $product['is_share'] = $share;

        $data = [
            "product" => $product,
            "main_img" => $main_img,
            "detail_img" => $detail_img,
            "activity_img" => $activity_img,
        ];
        return [
            'result'=>'success',
            'data'=>$data
        ];
    }


    /**
     * 商品详情列表
     * @param Request $request
     * @return array
     */
    public function productDetailList(Request $request){
        $validator = Validator::make($request->all(), [
            'ids' => 'required|array',
            "ids.*"=>'required|numeric'
        ]);
        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $list = Product::whereIn('id',$request->get('ids'))->get();
        return [
            "result"=>"success",
            "data"=>$list
        ];

    }


    /**
     * 购买记录
     * @param Request $request
     * @return array
     */
    public function buyRecord(Request $request){
        $validator = Validator::make($request->all(), [
            'product_id' => 'required|numeric',
        ]);
        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
//        $users = Product::where('id',$request->get('product_id'))->first()->users()->orderBy('created_at')->paginate(10);


        $order_products = OrderProduct::where('product_id',$request->get('product_id'))->with('user')->orderBy('created_at','desc')->paginate(10);

        $list = UserResource::collection($order_products);

        return [
            "result"=>"success",
            "data"=>[
                'data' => $list,
                'last_page' => $order_products->lastPage()
            ]
        ];
    }





}
